package com.zxx.coolweather._wuguan3_ok;

import java.io.IOException;

import okhttp3.Interceptor;
import okhttp3.MediaType;
import okhttp3.Protocol;
import okhttp3.Request;
import okhttp3.Response;
import okhttp3.ResponseBody;

/**
 * 模拟网络请求(添加自己的返回值)
 *
 * @author zxx on 2022/1/14
 */
public class SelfResponseInterceptor implements Interceptor {

    private String mUrl = "https://www.baidu.com/";

    public SelfResponseInterceptor(String mUrl) {
        this.mUrl = mUrl;
    }

    @Override
    public Response intercept(Chain chain) throws IOException {
        Request request = chain.request();
        String url = request.url().toString();
        //Log.e("Tag-->", "url= " + url);
        System.out.println("url=" + url);

        Response response;
        if (url.equals(mUrl)) {
            String responseString = "{\"message\":\"我是模拟的数据\"}";//模拟的错误的返回值
            response = new Response.Builder()
                    .code(400)
                    .request(request)
                    .protocol(Protocol.HTTP_1_0)
                    .body(ResponseBody.create(MediaType.parse("application/json"), responseString.getBytes()))
                    .addHeader("content-type", "application/json")
                    .message("self")    //需要这个，否则nullPointer
                    .build();
        } else {
            response = chain.proceed(request);
        }

        return response;
    }

}
